/**
 * 解析日期字符串，兼容 iOS 设备
 * @param {string|number|Date} dateStr - 日期字符串或时间戳
 * @returns {Date} 解析后的日期对象
 */
export function parseDate(dateStr) {
  if (!dateStr) return new Date();
  
  // 如果是时间戳
  if (typeof dateStr === 'number') {
    return new Date(dateStr);
  }
  
  // 如果是 Date 对象
  if (dateStr instanceof Date) {
    return dateStr;
  }
  
  // 处理日期字符串
  let date = null;
  
  // 处理非标准格式 (M/D/YY HH:mm AM/PM)
  const nonStandardFormat = /^(\d{1,2})\/(\d{1,2})\/(\d{2}) (\d{1,2}):(\d{2}) (AM|PM)$/;
  const match = dateStr.match(nonStandardFormat);
  if (match) {
    const [, month, day, year, hours, minutes, ampm] = match;
    let hour = parseInt(hours);
    if (ampm === 'PM' && hour < 12) hour += 12;
    if (ampm === 'AM' && hour === 12) hour = 0;
    
    // 转换为标准格式 (YYYY/MM/DD HH:mm:ss)
    const fullYear = parseInt('20' + year); // 假设年份是 20xx
    const formattedMonth = String(month).padStart(2, '0');
    const formattedDay = String(day).padStart(2, '0');
    const formattedHour = String(hour).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    
    dateStr = `${fullYear}/${formattedMonth}/${formattedDay} ${formattedHour}:${formattedMinutes}:00`;
  }
  
  // 尝试不同的标准日期格式
  const formats = [
    // yyyy/MM/dd
    /^(\d{4})\/(\d{2})\/(\d{2})$/,
    // yyyy/MM/dd HH:mm:ss
    /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,
    // yyyy-MM-dd
    /^(\d{4})-(\d{2})-(\d{2})$/,
    // yyyy-MM-dd HH:mm:ss
    /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,
    // yyyy-MM-ddTHH:mm:ss
    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/,
    // yyyy-MM-ddTHH:mm:ss+HH:mm
    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\+(\d{2}):(\d{2})$/
  ];
  
  for (const format of formats) {
    const match = dateStr.match(format);
    if (match) {
      if (format === formats[0]) { // yyyy/MM/dd
        date = new Date(match[1], match[2] - 1, match[3]);
      } else if (format === formats[1]) { // yyyy/MM/dd HH:mm:ss
        date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
      } else if (format === formats[2]) { // yyyy-MM-dd
        date = new Date(match[1], match[2] - 1, match[3]);
      } else if (format === formats[3]) { // yyyy-MM-dd HH:mm:ss
        date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
      } else if (format === formats[4]) { // yyyy-MM-ddTHH:mm:ss
        date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
      } else if (format === formats[5]) { // yyyy-MM-ddTHH:mm:ss+HH:mm
        date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
      }
      break;
    }
  }
  
  // 如果以上格式都不匹配，尝试使用原生 Date 解析
  if (!date) {
    date = new Date(dateStr);
  }
  
  // 如果解析失败，返回当前日期
  if (isNaN(date.getTime())) {
    console.warn(`无法解析日期字符串: ${dateStr}`);
    return new Date();
  }
  
  return date;
} 